#include<gflags/gflags.h>
#include<brpc/server.h>
#include<butil/logging.h>
#include<thread>
#include"main.pb.h"
#include"../../Common/etcd.hpp"
#include"../../Common/channel.hpp"
DEFINE_bool(log_mod,false,"true为发布模式,false为调试模式");
DEFINE_string(log_file,"","发布模式下日志存储的文件");
DEFINE_int32(log_level,0,"要输出的日志等级");
//1.将etcd监视与servicemanager的上下线服务关联 
//2.开启etcd的监视
//3.使用servicemanager调用echo服务管道测试服务
int main(int argc,char* argv[])
{
    google::ParseCommandLineFlags(&argc,&argv,true);
    zzy_mims::init_logger(FLAGS_log_mod,FLAGS_log_file,(spdlog::level::level_enum)FLAGS_log_level);

    const std::string etcd_host = "http://127.0.0.1:2379";//客户端注册中心地址
    const std::string service_dir = "/service/echo";//查询的服务
    const std::string basedir = "/service";//查询的根目录
    zzy_mims::ServChanManager scm;
    auto online = bind(&zzy_mims::ServChanManager::ServiceOnline,&scm,std::placeholders::_1,std::placeholders::_2);
    auto offline = bind(&zzy_mims::ServChanManager::ServiceOffline,&scm,std::placeholders::_1,std::placeholders::_2);
    scm.Declared(service_dir);

    std::shared_ptr<zzy_mims::Discovery> discovery = std::make_shared<zzy_mims::Discovery>(etcd_host,basedir,online,offline);
    while(true)
    {
        auto channel = scm.choose(service_dir);
        if(channel)
        {
            // 进行RPC调用
            ::example::EchoService_Stub stub(channel.get());
            ::example::EchoRequest req;
            req.set_message("你好 zzy");
            // 因为如果需要用到异步调用的时候，异步调用可能会直接对cntl和rep进行释放，所以不能简单定义到栈上
            brpc::Controller *cntl = new brpc::Controller();
            ::example::EchoResponse *resp = new ::example::EchoResponse();
             stub.Echo(cntl,&req,resp,nullptr);//同步调用
            if(cntl->Failed()==true)
                std::cout<<"RPC调用失败"<<cntl->ErrorText()<<std::endl;
            else
                std::cout<<"收到响应:"<<resp->message()<<std::endl;
            delete cntl;
            delete resp;
        }
        std::this_thread::sleep_for(chrono::seconds(2));
    }

}